package com.smartresume.backend.service;

import com.google.gson.Gson;
import com.smartresume.backend.model.AIServiceResponse;
import com.smartresume.backend.model.ResumeAnalysisResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 简历分析服务
 * 
 * @author SmartResume Team
 * @version 1.0.0
 */
@Service
public class ResumeAnalysisService {
    
    private static final Logger log = LoggerFactory.getLogger(ResumeAnalysisService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${ai.service.url:http://localhost:5005}")
    private String aiServiceUrl;
    
    @Bean
    public Gson gson() {
        return new com.google.gson.GsonBuilder()
                .disableHtmlEscaping()
                .create();
    }

    /**
     * 分析简历内容
     * 
     * @param resumeText 简历文本
     * @param industry 目标行业
     * @return 分析结果
     */
    public ResumeAnalysisResponse analyzeResume(String resumeText, String industry) {
        try {
            log.info("开始分析简历，文本长度: {}, 目标行业: {}", resumeText.length(), industry);
            
            // 调用AI服务
            AIServiceResponse aiResponse = callAIService(resumeText, industry);
            
            if (aiResponse == null || !aiResponse.isSuccess()) {
                log.error("AI服务调用失败: {}", aiResponse != null ? aiResponse.getError() : "响应为空");
                return createErrorResponse("AI服务暂时不可用，请稍后重试");
            }
            
            // 构建响应结果
            return ResumeAnalysisResponse.builder()
                    .success(true)
                    .message(aiResponse.getMessage())
                    .keywords(aiResponse.getKeywords())
                    .strengths(aiResponse.getStrengths())
                    .weaknesses(aiResponse.getWeaknesses())
                    .suggestions(aiResponse.getSuggestions())
                    .matchScore(aiResponse.getMatchScore() != null ? aiResponse.getMatchScore() : calculateMatchScore(aiResponse, industry))
                    .build();
                    
        } catch (Exception e) {
            log.error("简历分析过程中发生异常", e);
            return createErrorResponse("分析过程中发生错误，请稍后重试");
        }
    }

    /**
     * 调用AI服务进行分析
     * 
     * @param resumeText 简历文本
     * @param industry 目标行业
     * @return AI服务响应
     */
    private AIServiceResponse callAIService(String resumeText, String industry) {
        try {
            String url = aiServiceUrl + "/analyze";
            
            // 构建请求体，包含行业信息
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("resumeText", resumeText);  // 修改为AI服务期望的字段名
            requestBody.put("industry", industry);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Accept-Charset", "UTF-8");
            headers.set("Content-Type", "application/json; charset=UTF-8");
            
            HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            
            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                log.info("AI服务响应: {}", responseBody);
                
                Gson gson = gson();
                return gson.fromJson(responseBody, AIServiceResponse.class);
            } else {
                log.error("AI服务返回错误状态码: {}", response.getStatusCode());
                return null;
            }
            
        } catch (Exception e) {
            log.error("调用AI服务时发生异常", e);
            return null;
        }
    }

    /**
     * 计算职业匹配度评分
     * 
     * @param aiResponse AI分析结果
     * @param industry 目标行业
     * @return 匹配度评分 (0-100)
     */
    private Integer calculateMatchScore(AIServiceResponse aiResponse, String industry) {
        try {
            if (aiResponse == null || aiResponse.getKeywords() == null) {
                return 60; // 默认分数
            }
            
            // 基础分数
            int baseScore = 50;
            
            // 关键词匹配度加分 (最多30分)
            int keywordCount = aiResponse.getKeywords().size();
            int keywordScore = Math.min(keywordCount * 3, 30);
            
            // 行业相关性加分 (最多20分)
            int industryScore = calculateIndustryRelevance(aiResponse.getKeywords(), industry);
            
            // 总分计算
            int totalScore = baseScore + keywordScore + industryScore;
            
            // 确保分数在合理范围内
            return Math.max(30, Math.min(100, totalScore));
            
        } catch (Exception e) {
            log.error("计算匹配度评分时发生异常", e);
            return 65; // 异常时返回默认分数
        }
    }
    
    /**
     * 计算行业相关性得分
     * 
     * @param keywords 关键词列表
     * @param industry 目标行业
     * @return 行业相关性得分 (0-20)
     */
    private int calculateIndustryRelevance(java.util.List<String> keywords, String industry) {
        if (keywords == null || keywords.isEmpty() || industry == null) {
            return 10; // 默认得分
        }
        
        // 行业核心关键词权重映射
        java.util.Map<String, java.util.List<String>> industryKeywords = new java.util.HashMap<>();
        industryKeywords.put("technology", java.util.Arrays.asList("Java", "Python", "JavaScript", "React", "Vue", "Spring Boot", "MySQL", "Redis"));
        industryKeywords.put("finance", java.util.Arrays.asList("金融", "银行", "投资", "风控", "量化", "交易", "资产管理", "保险"));
        industryKeywords.put("education", java.util.Arrays.asList("教育", "培训", "教学", "课程设计", "学习管理", "在线教育"));
        industryKeywords.put("healthcare", java.util.Arrays.asList("医疗", "健康", "护理", "医学", "药学", "生物技术"));
        
        java.util.List<String> relevantKeywords = industryKeywords.getOrDefault(industry, java.util.Arrays.asList("管理", "沟通", "团队合作"));
        
        // 计算匹配的关键词数量
        long matchCount = keywords.stream()
                .filter(keyword -> relevantKeywords.stream()
                        .anyMatch(relevant -> relevant.toLowerCase().contains(keyword.toLowerCase()) || 
                                            keyword.toLowerCase().contains(relevant.toLowerCase())))
                .count();
        
        // 根据匹配度计算得分 (最多20分)
        return Math.min((int) matchCount * 4, 20);
    }

    /**
     * 创建错误响应
     * 
     * @param message 错误消息
     * @return 错误响应
     */
    private ResumeAnalysisResponse createErrorResponse(String message) {
        return ResumeAnalysisResponse.builder()
                .success(false)
                .message(message)
                .build();
    }
}